package com.ygl.utils;

import com.ygl.entity.User;
import org.springframework.cglib.beans.BeanMap;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ygl
 * @date 2021/7/7
 * @description 封装map工具类，支持map链式调用
 */
public class Maps {

    private Map<String, Object> paramMap = new HashMap<>();

    private Maps(String key, String value) {
        paramMap.put(key, value);
    }

    private Maps(String key, Object value) {
        paramMap.put(key, value);
    }

    public Maps() {
    }

    public Maps(Integer id) {
        paramMap.put("id", id);
    }

    // build构建maps对象,直接传id
    public static Maps build(Integer id) {
        return new Maps("id", id);
    }

    // build构建maps对象
    public static Maps build(String key, String value) {
        return new Maps(key, value);
    }

    // build构建maps对象
    public static Maps build(String key, Object value) {
        return new Maps(key, value);
    }

    public static Maps build() {
        return new Maps();
    }

    public Maps put(String key, String value) {
        paramMap.put(key, value);
        // this返回当前对象
        return this;
    }

    public Maps put(String key, Object value) {
        paramMap.put(key, value);
        // this返回当前对象
        return this;
    }

    public Maps put(Integer id) {
        paramMap.put("id", id);
        // this返回当前对象
        return this;
    }

    public Maps put(Map<String, Object> map) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            paramMap.put(entry.getKey(), entry.getValue());
        }
        return this;
    }

    public Map<String, Object> getMap() {
        return paramMap;
    }

    // 对象转map集合
    public <T> Map<String, Object> beanToMap(T bean) {
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                paramMap.put(key + "", beanMap.get(key));
            }
        }
        return paramMap;
    }

    // 对象转map集合
    public <T> Map<String, Object> beanToMapUpdate(T bean) {
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                paramMap.put("update" + upperFirstLetter(key + ""), beanMap.get(key));
            }
        }
        return paramMap;
    }

    // 首字母转大写
    public static String upperFirstLetter(String str) {
        char[] chars = str.toCharArray();
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            chars[0] = (char) (chars[0] - 32);
        }
        return new String(chars);
    }
}

